package com.newangels.listener;

import com.newangels.service.AgentManagerService;
import com.newangels.util.startAgent;
import jade.Boot;
import jade.core.Profile;
import jade.util.leap.Properties;
import jade.wrapper.gateway.JadeGateway;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import static com.newangels.service.impl.AgentManagerServiceImpl.getAgentManagerServiceImpl;

/**
 * 随tomcat启动Agent以及关闭tomcat时修改数据库数据
 *
 * @author: TangLiang
 * @date: 2020/5/25 10:52
 * @since: 1.0
 */
@WebListener
public class SystemListener implements ServletContextListener {
    private static Logger logger = Logger.getLogger(SystemListener.class.getName());
    AgentManagerService agentManagerService = getAgentManagerServiceImpl();

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //配置容器
        String[][] agents = {{"-gui"}};
        //启动主容器
        Arrays.stream(agents).forEach(Boot::main);
        //查询数据库状态为启动的agent 启动
        List<Map<String, Object>> list = agentManagerService.selectAgents(null, null, null, null, null, "1", "1", null, null, -1, -1);
        if (list != null) {
            String[] args = new String[3];
            try {
                for (Map<String, Object> map : list) {
                    args[0] = (String) map.get("AGENT_CODE_");
                    args[1] = (String) map.get("AGENT_URL_");
                    args[2] = (String) map.get("AGENT_ARGUMENTS_");
                    startAgent.main(args);
                }
            } catch (RuntimeException e) {
                logger.warning(args[0] + "Agent start failed\n" + e.getMessage());
                e.printStackTrace();
            }
        }
        //启动 KillAgentGatewayAgent
        Properties pp = new Properties();
        pp.setProperty(Profile.MAIN, "false");
        pp.setProperty("container-name", "KillAgentGatewayAgent");
        JadeGateway.init("com.newangels.agent.KillAgentGatewayAgent", pp);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        //修改数据库所有Agent状态为未启动
        agentManagerService.updateAllAgentState("0", "1");
        JadeGateway.shutdown();
    }
}
